<template>
  <div ref="containerRef" class="common-container equipment-wrap">
    <div ref="searchRef" class="common-search-view">
      <t-form ref="formRef" :data="formData" :colon="true" layout="inline" :label-width="0">
        <form-item v-for="(item, index) in list" :key="index" :form-data="formData" :data="item"></form-item>
        <div class="opt">
          <div class="item">
            <t-button class="common-button" theme="primary" @click="search">搜索</t-button>
            <t-button class="common-button" variant="outline" @click="reset">重置</t-button>
          </div>
          <div class="item">
            <t-button class="common-button" theme="primary" @click="create">新增</t-button>
          </div>
        </div>
      </t-form>
    </div>
    <div class="common-table-wrap shadow" :style="{ height: `calc(100% - ${searchHeight}px)` }">
      <t-base-table class="common-table" row-key="index" :data="tableData" max-height="100%" :columns="columns">
        <template #enable="{ row }">
          <t-switch
            v-model="row.enable"
            size="large"
            :label="['ON', 'OFF']"
            :loading="row.loading"
            @click="clickeSwitch(row)"
          ></t-switch>
        </template>
        <template #type="{ row }">
          <div class="device-type" :style="{ backgroundColor: VIDEOTYPE_BG_COLOR[row.type] }">
            {{ VIDEOTYPE_NAME[row.type] }}
          </div>
        </template>
        <template #videoUrl="{ row }">
          <t-popup :content="row.videoUrl" placement="top" :show-arrow="true" :destroy-on-close="true">
            <t-link class="omit" theme="primary" :underline="true">{{ row.videoUrl }}</t-link>
          </t-popup>
        </template>
        <template #opt="{ row }">
          <div class="common-options">
            <div class="item" @click="detail(row)">
              <svg-icon class="icon" name="options-detail" />
              <t-link theme="primary" class="link" :underline="true">详情</t-link>
            </div>
            <div class="item" @click="update(row)">
              <svg-icon class="icon" name="options-edit " />
              <t-link theme="primary" class="link" :underline="true">编辑</t-link>
            </div>
            <t-dropdown
              :options="dropdownOptions"
              :min-column-width="120"
              style="text-align: center"
              trigger="click"
              @click="handleClickDropdown"
            >
              <div class="item">
                <svg-icon class="icon" name="options-more" />
                <t-link theme="primary" class="link" :underline="true">更多</t-link>
                <svg-icon class="icon" name="options-down_arrow" />
              </div>
            </t-dropdown>
          </div>
        </template>
      </t-base-table>
      <pagination-view
        v-if="!!pageData.total"
        :current="pageData.params.page"
        :total="pageData.total"
        :page-size="pageData.params.size"
        @page-change="handlePageChange"
      ></pagination-view>
    </div>
    <edit-dialog
      ref="editDialogRef"
      :title="actionValue.deviceName"
      :data="actionValue"
      @sure="getData"
      @cancel="closeEdit"
    ></edit-dialog>
  </div>
</template>

<script setup lang="ts">
import { tryit } from 'radash';
// import { MessagePlugin } from 'tdesign-vue-next';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import mockApi from '@/api/mock';
import { ListParams, ResultItem } from '@/api/model/mockModel';
import { SUCCESS_CODE } from '@/constants';
import { VIDEOTYPE_BG_COLOR, VIDEOTYPE_NAME } from '@/constants/data';
import { useListPage } from '@/hooks/useListPage';
import { useLoading } from '@/hooks/useLoading';
import { useTableHeight } from '@/hooks/useTableHeight';

import EditDialog from './comopnents/EditDialog.vue';
import { columns, INIT_DATA, list } from './datas/index';

const router = useRouter();

const editDialogRef: any = ref(null);
const containerRef = ref<HTMLDivElement>();
// const messageDialogRef = ref();
const actionValue: any = ref({});

const formData = ref({ ...INIT_DATA });
const tableData = ref([]);
const detailData = ref<ResultItem>();
const dropdownOptions = ref([
  { content: 'GA1400设置', value: 1 },
  { content: 'GB28181设置', value: 2 },
  { content: '设备连接测试', value: 3 },
  { content: '删除', value: 4 },
]);

const { pageData, handlePageChange, search, reset, formRef } = useListPage(getData);
const { searchRef, searchHeight } = useTableHeight();
const { loadingStart, loadingEnd } = useLoading(containerRef);

const handleClickDropdown = (data: any) => {
  const { content } = data;
  console.log('content', data, content);
};

const create = () => {
  detailData.value = null;
  router.push('equipmentAdd');
};

const update = (data: ResultItem) => {
  detailData.value = data;
  router.push({
    path: 'equipmentEdit',
    query: { id: data.id },
  });
};

const detail = (data: ResultItem) => {
  detailData.value = data;
  router.push({
    path: 'equipmentDetail',
    query: { id: data.id },
  });
};

// const messageDialogSure = async () => {
//   const [err, res] = await tryit(mockApi.del)({ id: detailData.value.id });

//   if (!err && res.code === SUCCESS_CODE) {
//     messageDialogRef.value.close();
//     await MessagePlugin.success('操作成功');
//     await getData();
//   }
// };

async function getData() {
  loadingStart();

  const postData: ListParams = { ...pageData.params, search: { ...formData.value } };
  const [err, res] = await tryit(mockApi.list)(postData);

  if (!err && res.code === SUCCESS_CODE) {
    const { list, total } = res.data;
    list.map((item: any) => {
      item.loading = false;
      return item;
    });
    tableData.value = list;
    pageData.total = total;
  }
  loadingEnd();
}

// 启用禁用
const clickeSwitch = (data: any) => {
  actionValue.value = { ...data };
  actionValue.value.enable = !actionValue.value.enable;
  editDialogRef.value.open();
  tableData.value.map((item: any) => {
    if (item.id === data.id) {
      item.loading = !item.loading;
    }
    return item;
  });
};
const closeEdit = () => {
  editDialogRef.value.close();
  tableData.value.map((item: any) => {
    if (item.id === actionValue.value.id) {
      item.enable = !item.enable;
      item.loading = !item.loading;
    }
    return item;
  });
  actionValue.value = {};
};

onMounted(() => {
  getData();
});
</script>

<style lang="less" scoped>
.equipment-wrap {
  .device-type {
    color: #fff;
    display: inline-block;
    padding: 3px 8px;
    border-radius: 3px;
    font-size: 14px;
  }
}
</style>
